package com.ssm.controller;

import com.github.pagehelper.PageInfo;
import com.ssm.entity.Book;
import com.ssm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Controller
@RestController
@RequestMapping("/books")
public class BookControllerResult {
    @Autowired
    private BookService bookService;
    //查所有
    @GetMapping
    public Result getList(){
        List<Book> bookList = bookService.findAll();
        Integer code  = bookList!=null?Code.GET_OK:Code.GET_ERR;
        String msg  = bookList!=null?"":"数据库查询失败，请重试";
        return  new Result(code,bookList,msg);
    }
    //查一个
//    @RequestMapping(value ="/book/{id}",method = RequestMethod.GET)
    @GetMapping("/{id}")
    public Result getBook(@PathVariable("id") Integer id){
        Book book = bookService.findById(id);
        Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
        String msg = book != null ? "" : "数据查询失败，请重试！";
        return  new Result(code,book,msg);
    }
    //分页查询
    //查一个
//    @RequestMapping(value ="/book/{pageNum}/{pageSize}",method = RequestMethod.GET)
    @GetMapping("/{pageNum}/{pageSize}")
    public Result pageFind(@PathVariable("pageNum") Integer pageNum,@PathVariable("pageSize") Integer pageSize){
        PageInfo<Book> pageInfo = bookService.findPaged(pageNum, pageSize);
        Map<String,Object> map  = new HashMap<>();
        map.put("pageTotal",pageInfo.getTotal());
        map.put("bookList",pageInfo.getList());
        Integer code = pageInfo.getList()!= null ? Code.GET_OK : Code.GET_ERR;
        String msg = pageInfo.getList()!= null ? "" : "数据查询失败，请重试！";
        return  new Result(code,map,msg);
    }

    //保存
//    @RequestMapping(value = "/book",method = RequestMethod.POST)
    @PostMapping
    public Result save(@RequestBody Book book){
      boolean flag =  bookService.save(book);
//        System.out.println(book);
        return new Result(flag?Code.SAVE_OK:Code.SAVE_ERR,flag);
    }
//    @RequestMapping(value = "/book",method = RequestMethod.PUT)
    @PutMapping
    public Result toUpdate(@RequestBody Book book){
      boolean flag =   bookService.update(book);
        return  new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }
    //查一个
//    @RequestMapping(value ="/book/{id}",method = RequestMethod.DELETE)
    @DeleteMapping("/{id}")
    public Result delBook(@PathVariable("id") Integer id){
       boolean flag = bookService.deleteById(id);
        return  new Result(flag?Code.DELETE_OK:Code.DELETE_ERR,flag);
    }
}
